package shorturl.generator.shorter;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.experimental.Accessors;
import shorturl.base.IShorterGenerator;
import shorturl.IShorterStorage;
import shorturl.IStringGenerator;
import shorturl.entity.ShorterString;

/**
 * 不附带任何属性的短链接对象生成器
 */
@Data
@Accessors(chain = true)
@AllArgsConstructor
public class ShorterStringGenerator implements IShorterGenerator<ShorterString> {

    /**
     * 使用的短链接字符串生成器
     */
    private IStringGenerator generator;
    /**
     * 使用的短链接存储器
     */
    private IShorterStorage shorterStorage;

    /**
     * 生成短链接实体对象
     * @param url 原始链接
     * @return
     */
    @Override
    public ShorterString generate(String url) {
        String shorterString = generator.generate(url);
        while (shorterStorage.hasShorterString(shorterString)) {
            shorterString = generator.generate(url);
        }
        ShorterString shorter = new ShorterString(shorterString, url);
        shorterStorage.save(url, shorter);
        return shorter;
    }
}
